<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    <meta name="sogou_site_verification" content="true">
    
    
    
    <title>BIO与NIO与多路复用 | Lvshen&#39;s Blog | This is My World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="IO,多路复用">
    <meta name="baidu-site-verification" content="VIVNdSiMZm">
    <meta name="description" content="什么是IO首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。 举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要将数据从用户空间拷贝到操作系统内核空间，再由内核空间将数据写入到磁盘中。读取也是一样，都需要经过内核空间。这里主要将网络的IO。">
<meta name="keywords" content="IO,多路复用">
<meta property="og:type" content="article">
<meta property="og:title" content="BIO与NIO与多路复用">
<meta property="og:url" content="https://lvshen9.gitee.io/2020/05/07/1/index.html">
<meta property="og:site_name" content="Lvshen&#39;s Blog">
<meta property="og:description" content="什么是IO首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。 举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要将数据从用户空间拷贝到操作系统内核空间，再由内核空间将数据写入到磁盘中。读取也是一样，都需要经过内核空间。这里主要将网络的IO。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YZmepT.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVHxDs.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVbgZn.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVbXi6.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVOGMF.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVxxAJ.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YVzEHe.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/05/07/YZSzS1.png">
<meta property="og:updated_time" content="2020-05-07T01:48:52.634Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="BIO与NIO与多路复用">
<meta name="twitter:description" content="什么是IO首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。 举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要将数据从用户空间拷贝到操作系统内核空间，再由内核空间将数据写入到磁盘中。读取也是一样，都需要经过内核空间。这里主要将网络的IO。">
<meta name="twitter:image" content="https://s1.ax1x.com/2020/05/07/YZmepT.png">
    
    <link rel="shortcut icon" href="/img/mylogo.jpg">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">我的技术小房间</h5>
          <a href="mailto:https://lvshen9.github.io" title="https://lvshen9.github.io" class="mail">https://lvshen9.github.io</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-address-book"></i>
                About
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/collection"  >
                <i class="icon icon-lg icon-apple"></i>
                Collection
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://lvshen9.github.io/" target="_blank" >
                <i class="icon icon-lg icon-wordpress"></i>
                Blog
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/lvshen9" target="_blank" >
                <i class="icon icon-lg icon-github-alt"></i>
                GitHub
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">BIO与NIO与多路复用</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">BIO与NIO与多路复用</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-05-07T00:02:35.000Z" itemprop="datePublished" class="page-time">
  2020-05-07
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#什么是IO"><span class="post-toc-number">1.</span> <span class="post-toc-text">什么是IO</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#BIO"><span class="post-toc-number">2.</span> <span class="post-toc-text">BIO</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#NIO"><span class="post-toc-number">3.</span> <span class="post-toc-text">NIO</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#多路复用"><span class="post-toc-number">4.</span> <span class="post-toc-text">多路复用</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#Selector-NIO"><span class="post-toc-number">4.1.</span> <span class="post-toc-text">Selector NIO</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#Epoll-NIO"><span class="post-toc-number">4.2.</span> <span class="post-toc-text">Epoll NIO</span></a></li></ol></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#总结"><span class="post-toc-number">5.</span> <span class="post-toc-text">总结</span></a></li></ol>
        </nav>
    </aside>


<article id="post-1"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">BIO与NIO与多路复用</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-05-07 08:02:35" datetime="2020-05-07T00:02:35.000Z"  itemprop="datePublished">2020-05-07</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h4 id="什么是IO"><a href="#什么是IO" class="headerlink" title="什么是IO"></a>什么是IO</h4><p>首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。</p>
<p>举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要将数据从用户空间拷贝到操作系统内核空间，再由内核空间将数据写入到磁盘中。读取也是一样，都需要经过内核空间。这里主要将网络的IO。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YZmepT.png" alt="系统调用" title>
                </div>
                <div class="image-caption">系统调用</div>
            </figure>
<a id="more"></a>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVHxDs.png" alt="网络IO模型" title>
                </div>
                <div class="image-caption">网络IO模型</div>
            </figure>
<p>上图为网络IO模型</p>
<h4 id="BIO"><a href="#BIO" class="headerlink" title="BIO"></a>BIO</h4><p>顾名思义，Blocking IO，阻塞IO，以前传统的网络IO为阻塞IO，Java代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BioServerTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> ExecutorService threadPool = Executors.newCachedThreadPool();</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        ServerSocket socket = <span class="keyword">new</span> ServerSocket(<span class="number">8082</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            Socket accept = socket.accept();<span class="comment">//可能出现阻塞</span></span><br><span class="line">            threadPool.submit(() -&gt; &#123;</span><br><span class="line">                <span class="keyword">byte</span>[] request = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line"></span><br><span class="line">                accept.getInputStream().read(request);<span class="comment">//可能出现阻塞</span></span><br><span class="line">                Thread.sleep(<span class="number">60000</span>); <span class="comment">//测试模拟阻塞</span></span><br><span class="line">                System.out.println(<span class="keyword">new</span> String(request));</span><br><span class="line">                <span class="keyword">return</span>  request.toString();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如上，在获取客户端<code>accept</code>和读取数据<code>read</code>时会出现阻塞。这时其他客户端就会无法连接，从而导致连接的浪费（一个客户端是一个线程）。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVbgZn.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>我们将代码在读取的时候阻塞了60s，客户端一连接，输入数据，这里阻塞。客户端二也会阻塞。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVbXi6.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>客户端1释放后，客户端2才能继续。</p>
<blockquote>
<p>因为阻塞的API设计，存在线程资源浪费的情况<br>每一个请求都有一个线程处理<br>不管连接有没有数据传输，我都安排一个线程去处理</p>
</blockquote>
<h4 id="NIO"><a href="#NIO" class="headerlink" title="NIO"></a>NIO</h4><p>非阻塞IO，就是为了解决BIO产生的问题。早先的NIO是将多个客户端放入一个集合中，应用程序轮番遍历，读取数据。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVOGMF.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>上图（白嫖的）为普通NIO的模型，这里有个问题，虽然不是BIO了，不会产生阻塞，但是如果有10万个客户端，应用程序要轮询10万次客户端并且read数据，这里read数据是调用了内核的，发生了系统调用10万次。用户态到内核态的切换需要成本，如果切换过于频繁，有损系统性能。</p>
<h4 id="多路复用"><a href="#多路复用" class="headerlink" title="多路复用"></a>多路复用</h4><h5 id="Selector-NIO"><a href="#Selector-NIO" class="headerlink" title="Selector NIO"></a>Selector NIO</h5><p>随着技术的发展，人们想到，可以通过一次系统调用，将客户端连接放入操作系统内核，返回可读的连接给应用程序。应用程序自己读写。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVxxAJ.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>如上图，只需一次selector系统调用，accept连接放入了内核。</p>
<p>Java代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SocketSelectorSingleThread</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> ServerSocketChannel server = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">private</span> Selector selector = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> port = <span class="number">9090</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        initServer();</span><br><span class="line">        System.out.println(<span class="string">"服务器启动了....."</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                <span class="keyword">while</span> (selector.select(<span class="number">0</span>) &gt; <span class="number">0</span>) &#123;<span class="comment">//访问内核有没有事件</span></span><br><span class="line">                    Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();</span><br><span class="line">                    Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();</span><br><span class="line">                    <span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">                        SelectionKey key = iterator.next();</span><br><span class="line">                        iterator.remove();</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">if</span> (key.isAcceptable()) &#123;</span><br><span class="line">                            acceptHandler(key);</span><br><span class="line">                        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isReadable()) &#123;</span><br><span class="line">                            readHandler(key);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initServer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            server = ServerSocketChannel.open();</span><br><span class="line">            server.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">            server.bind(<span class="keyword">new</span> InetSocketAddress(port));</span><br><span class="line">            selector = Selector.open();</span><br><span class="line">            server.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">acceptHandler</span><span class="params">(SelectionKey key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();</span><br><span class="line">            SocketChannel client = ssc.accept();</span><br><span class="line">            client.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">            ByteBuffer buffer = ByteBuffer.allocate(<span class="number">8192</span>);</span><br><span class="line">            client.register(selector, SelectionKey.OP_READ, buffer);</span><br><span class="line">            System.out.println(<span class="string">"------------------------"</span>);</span><br><span class="line">            System.out.println(<span class="string">"新客户端: "</span> + client.getRemoteAddress());</span><br><span class="line">            System.out.println(<span class="string">"------------------------"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">readHandler</span><span class="params">(SelectionKey key)</span> </span>&#123;</span><br><span class="line">        SocketChannel client = (SocketChannel) key.channel();</span><br><span class="line">        ByteBuffer buffer = (ByteBuffer) key.attachment();</span><br><span class="line"></span><br><span class="line">        buffer.clear();</span><br><span class="line">        <span class="keyword">int</span> read = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line"></span><br><span class="line">                read = client.read(buffer);</span><br><span class="line">                <span class="keyword">if</span> (read &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    buffer.flip();</span><br><span class="line">                    <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">                        client.write(buffer);</span><br><span class="line">                        System.out.println(<span class="string">"读到客户端数据: "</span> + <span class="keyword">new</span> String(buffer.array()));</span><br><span class="line">                    &#125;</span><br><span class="line">                    buffer.clear();</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (read == <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    client.close();</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SocketSelectorSingleThread server = <span class="keyword">new</span> SocketSelectorSingleThread();</span><br><span class="line">        server.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>测试结果如下：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YVzEHe.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>技术发展到这里可能会觉得很不错了，只发生了一次系统调用，但其实还有问题。每新增一个客户端，select函数会将所有的客户端加载进入内核，这个过程并不优雅。还有每次内核都要循环遍历O(n)次，对于内核来说是不是还有可优化的空间呢。</p>
<h5 id="Epoll-NIO"><a href="#Epoll-NIO" class="headerlink" title="Epoll NIO"></a>Epoll NIO</h5><p>epoll的多路复用有什么优点呢，先来一张图：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/05/07/YZSzS1.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>如上图，将之前的select函数换成了epoll函数，epoll函数发生的系统调用，内核会开辟出两个空间，会将客户端连接放入缓存空间1，当有数据时，通过事件驱动将有值的连接放入缓存空间2，应用程序获取有值的连接。内核中的时间复杂度为O(1)。</p>
<h4 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h4><blockquote>
<p>BIO：如果其中有一个客户端阻塞，其他客户端是无法获取连接，BIO采用的办法是多线程，每个线程是一个客户端，如果，一个线程阻塞切换到另外一个线程。问题是：线程创建耗内存，如果线程很多，不划算另外，线程的切换也是有耗性能的<br>NIO：N个客户端连接放入集合中，应用程序读取数据时，循环遍历客户端，应用程序方面发生的系统调用是O(n)<br>多路复用器：selector，将n个客户端连接通过多路复用器，放入操作系统内核中，让内核进行遍历有数据的客户端数据，在应用程序方面，发生的系统调用是O(1),但内核中的遍历时间复杂度是O(n)；epoll，有事件驱动，内核中只会遍历有数据的客户端，内核遍历客户端的时间<br>复杂度为O(1)</p>
</blockquote>
<p>多路复用很多中间件都有使用，如kafka，redis，nginx等</p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-05-07T01:48:52.634Z" itemprop="dateUpdated">2020-05-07 09:48:52</time>
</span><br>


        
        原文链接：<a href="/2020/05/07/1/" target="_blank" rel="external">https://lvshen9.gitee.io/2020/05/07/1/</a>
        
    </div>
    
    <footer>
        <a href="https://lvshen9.gitee.io">
            <img src="/img/avatar.jpg" alt="我的技术小房间">
            我的技术小房间
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/IO/">IO</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/多路复用/">多路复用</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2020/05/07/1/&title=《BIO与NIO与多路复用》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2020/05/07/1/&title=《BIO与NIO与多路复用》 — Lvshen's Blog&source=什么是IO首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。
举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2020/05/07/1/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《BIO与NIO与多路复用》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2020/05/07/1/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2020/05/07/1/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2020/05/24/1/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">我在github上的Java项目</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2020/04/28/1/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">腾讯云算法面试题-给定边界输出对应索引下标</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "dy9kXHwg5jQUlLryQmpjWRlM-gzGzoHsz",
            appKey: "P9Nh39Ol0JbMMiYqNGHEP3ml",
            avatar: "mm",
            placeholder: "Just go go",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="https://lvshen9.github.io/blog2/pay/weixin.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="https://lvshen9.github.io/blog2/pay/weixin.jpg" data-alipay="https://lvshen9.github.io/blog2/pay/zhifu.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>我的技术小房间 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2020/05/07/1/&title=《BIO与NIO与多路复用》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2020/05/07/1/&title=《BIO与NIO与多路复用》 — Lvshen's Blog&source=什么是IO首先需要了解下什么是IO，IO就是读入/写出数据的过程，和等待读入/写出数据的过程。
举个列子，应用程序想要将数据写到操作系统磁盘文件中，是需要..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2020/05/07/1/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《BIO与NIO与多路复用》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2020/05/07/1/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2020/05/07/1/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://lvshen9.gitee.io/2020/05/07/1/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
